package com.example.ocrdemo;

import com.example.ocrdemo.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.ai.cv.common.ConnectionCallback;
import ohos.ai.cv.common.VisionConfiguration;
import ohos.ai.cv.common.VisionImage;
import ohos.ai.cv.common.VisionManager;
import ohos.ai.cv.text.ITextDetector;
import ohos.ai.cv.text.Text;
import ohos.ai.cv.text.TextConfiguration;
import ohos.ai.cv.text.TextDetectType;
import ohos.location.Locator;
import ohos.media.image.Image;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.InputStream;
import java.util.Locale;

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());

        VisionManager.init(this, new ConnectionCallback() {
            @Override
            public void onServiceConnect() {
                ITextDetector detector = VisionManager.getTextDetector(MainAbility.this);
                String filePath = String.format(Locale.ROOT, "assets/entry/resources/base/media/%s", "image.png");
                InputStream stream = this.getClass().getClassLoader().getResourceAsStream(filePath);
                ImageSource.SourceOptions options = new ImageSource.SourceOptions();

                ImageSource source = ImageSource.create(stream, options);
                ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
                PixelMap pixelMap = source.createPixelmap(decodingOpts);
                VisionImage image = VisionImage.fromPixelMap(pixelMap);
                TextConfiguration.Builder builder = new TextConfiguration.Builder();
                builder.setProcessMode(VisionConfiguration.MODE_IN);
                builder.setDetectMode(TextDetectType.TYPE_TEXT_DETECT_FOCUS_SHOOT);
                builder.setLanguage(TextConfiguration.CHINESE);
                TextConfiguration configuration = builder.build();
                detector.setVisionConfiguration(configuration);
                Text text = new Text();
                int result = detector.detect(image, text, null);
                ohos.agp.components.Text textComp = findComponentById(ResourceTable.Id_result_text);
                textComp.setText(text.getValue());
            }

            @Override
            public void onServiceDisconnect() {

            }
        });

    }
}
